Evaluate Reverse Polish Notation

Evaluate the value of an arithmetic expression in Reverse Polish Notation.

Valid operators are +, -, *, /. Each operand may be an integer or another expression.

Some examples:

  1. ["2", "1", "+", "3", "*"] -> ((2 + 1) * 3) -> 9
  2. ["4", "13", "5", "/", "+"] -> (4 + (13 / 5)) -> 6

Solution:

  1. public class Solution {
  2. public int evalRPN(String[] a) {
  3. Stack<Integer> stack = new Stack<Integer>();
  4. for (int i = 0; i < a.length; i++) {
  5. switch (a[i]) {
  6. case "+":
  7. stack.push(stack.pop() + stack.pop());
  8. break;
  9. case "-":
  10. stack.push(-stack.pop() + stack.pop());
  11. break;
  12. case "*":
  13. stack.push(stack.pop() * stack.pop());
  14. break;
  15. case "/":
  16. int n1 = stack.pop(), n2 = stack.pop();
  17. stack.push(n2 / n1);
  18. break;
  19. default:
  20. stack.push(Integer.parseInt(a[i]));
  21. }
  22. }
  23. return stack.pop();
  24. }
  25. }